package HBase;

import org.apache.hadoop.hbase.NamespaceNotFoundException;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;

import java.io.IOException;

/**
 * @Author lixinlei
 * @Date 2023/3/30 9:27
 */
public class Tools {

    /**
     * 判断某个namespace是否存在的方法
     * @param admin
     * @param nsName
     * @return
     */
    public static boolean isNamespaceExists(Admin admin,String nsName){

        boolean flag = true;

        try {
            admin.getNamespaceDescriptor(nsName);
        } catch (NamespaceNotFoundException nse){
            System.out.println("当前 "+nsName+" namespace不存在。");
            flag = false;
        } catch (IOException e){
            e.printStackTrace();
        }

        return flag;
    }

    /**
     * 判断表是否存在
     * @param admin
     * @param tbName
     * @return
     */
    public static boolean isTableExists(Admin admin,String tbName){

        boolean flag = true;

        try {
            flag = admin.tableExists(TableName.valueOf(tbName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return flag;
    }

    /**
     * 关闭 admin
     * @param admin
     */
    public static void closed(Admin admin){
        closed(admin,null);
    }

    /**
     * 关闭 admin 和 conn
     * @param admin
     * @param conn
     */
    public static void closed(Admin admin, Connection conn){
        try{
            if(admin!=null){
                admin.close();
            }
            if(conn!=null){
                conn.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}
